import fs from 'fs-extra'
import path from 'path'
import { app } from 'electron'

export interface Student {
  id: number
  studentId: string
  name: string
  attempts: number
  accuracy: number
  points: number
}
export interface Shortcut {
  id: string
  name: string
  backgroundColor: string
  backgroundImage: string
}

interface Database {
  students: Student[]
  shortcuts: Shortcut[]
}

const getDataFilePath = (): string => {
  return path.join(app.getPath('userData'), 'data.json')
}

export const initializeDb = async (): Promise<void> => {
  const filePath = getDataFilePath()
  const exists = await fs.pathExists(filePath)
  if (!exists) {
    const initialData: Database = {
      students: [],
      shortcuts: []
    }
    await fs.outputJson(filePath, initialData, { spaces: 2 })
  }
}

// 读取数据
const readDb = async (): Promise<Database> => {
  const filePath = getDataFilePath()
  try {
    const data: Database = await fs.readJson(filePath)
    return data
  } catch (error) {
    console.error('读取数据库失败:', error)
    throw error
  }
}

// 写入数据
const writeDb = async (data: Database): Promise<void> => {
  const filePath = getDataFilePath()
  try {
    await fs.writeJson(filePath, data, { spaces: 2 })
  } catch (error) {
    console.error('写入数据库失败:', error)
    throw error
  }
}

// 插入学生数据
export const insertStudent = async (
  studentId: string,
  name: string,
  attempts: number = 0,
  accuracy: number = 0,
  points: number = 0
): Promise<void> => {
  const data = await readDb()

  const newId = data.students.length > 0 ? data.students[data.students.length - 1].id + 1 : 1

  const newStudent: Student = {
    id: newId,
    studentId,
    name,
    attempts,
    accuracy,
    points,
  }

  data.students.push(newStudent)
  await writeDb(data)
}
export const removeStudents = async (id: number): Promise<void> => {
  const data = await readDb()
  data.students = data.students.filter(s => s.id !== id)
  await writeDb(data)
}

export const getAllStudents = async (): Promise<Student[]> => {
  const data = await readDb()
  return data.students
}

// 插入快捷方式
export const insertShortcut = async (shortcut: Shortcut): Promise<void> => {
  const data = await readDb()
  data.shortcuts.push(shortcut)
  await writeDb(data)
}
// 移除快捷方式
export const removeShortcut = async (id: string): Promise<void> => {
  const data = await readDb()
  data.shortcuts = data.shortcuts.filter(s => s.id !== id)
  await writeDb(data)
}

// 获取所有快捷方式
export const getAllShortcuts = async (): Promise<Shortcut[]> => {
  const data = await readDb()
  return data.shortcuts
}
export default initializeDb
